
package com.rx.mgt.controller;  

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rx.mgt.domain.Domain;
import com.rx.mgt.domain.DomainInfoExt;
import com.rx.mgt.service.DomainInfoExtService;
import com.rx.mgt.util.ExcelUtil;
import com.rx.mgt.util.PoiExcelUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rx.mgt.domain.AdminUser;
import com.rx.mgt.domain.UserInfoExt;
import com.rx.mgt.po.UsersBo;
import com.rx.mgt.service.DomainService;
import com.rx.mgt.service.SysLogService;
import com.rx.mgt.service.UserInfoExtService;
import com.rx.mgt.util.IpUtil;

/** 
 * ClassName:UserInfoExtController 
 * Function :
 * Reason   : 
 * Date     :Jan 31, 2017 9:35:30 PM 
 * @author   luolei 
 * @since    JDK 1.6
 */
@Controller
public class UserInfoExtController {

    @Autowired
    UserInfoExtService userInfoExtService;
    @Autowired
    DomainService domainService;
    @Autowired
    SysLogService sysLogService;
    @Autowired
    DomainInfoExtService domainInfoExtService;
    
    @RequestMapping(value="/users-list.htmlx")
    public String  login(ModelMap model,HttpServletRequest request ,UsersBo usersBo){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        if("2".equals(user.getType())){
            usersBo.setDomain(user.getDomain());
        }
    	List list = userInfoExtService.getAllUser(usersBo);
    	model.addAttribute("list",list);
    	model.addAttribute("usersBo",usersBo);
        System.out.println("111111111111111");
        return "user/users-list";
    }
    @RequestMapping(value="/users-add-all.htmlx")
    public String  usersAddAll(ModelMap model,UserInfoExt userInfoExt){
//        List list = userInfoExtService.getAllUser(userInfoExt);
//        model.addAttribute("list",list);
        System.out.println("111111111111111");
        return "user/users-add-all";
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value="/users-add.htmlx")
    public String  add(ModelMap model,HttpServletRequest request,UserInfoExt userInfoExt){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        UsersBo usersBo = new UsersBo();
        String domain1 = request.getParameter("domain");
        if("2".equals(user.getType())){
            domain1 = user.getDomain();
            usersBo.setDomain(user.getDomain());
        }
        if("3".equals(user.getType())){
            List list = domainService.getDomainInfoExt(usersBo);
            if(list!=null&&list.size()>0&& org.apache.commons.lang.StringUtils.isBlank(domain1)){
                Domain domain = (Domain) list.get(0);
                domain1 = domain.getDomain_name();

            }
            model.addAttribute("domainList",list);
            model.addAttribute("domain1",domain1);

        }
        DomainInfoExt domainInfoExtByDomain = domainInfoExtService.getDomainInfoExtByDomain(domain1);
        model.addAttribute("domainModel",domainInfoExtByDomain);
        Map map =new HashMap();
        map.put("result", "success");
        if(StringUtils.isEmpty(userInfoExt.getId())){


            model.addAttribute("users",userInfoExt);
            model.addAttribute("method","add");
            return "user/users-add";
        }
        UserInfoExt info= userInfoExtService.get(userInfoExt.getId());
        if(info!=null){
            String userName=info.getUser_name();
            info.setUser_name(userName.substring(0, userName.indexOf("@")));
            model.addAttribute("users",info);
        }
        System.out.println("111111111111111");
        return "user/users-add";
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value="/userSave.htmlx")
    @ResponseBody
    public Map  userSave(HttpServletRequest request ,ModelMap model,UserInfoExt userInfoExt){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        sysLogService.add("更新用户信息", IpUtil.getIpAddr(request), "管理", user.getId()+"", user.getUser_name());
        Map map =new HashMap();
        map.put("result", "success");
        userInfoExt.setUser_name(userInfoExt.getUser_name()+"@"+userInfoExt.getDomain());
        userInfoExtService.changeUserInfo(userInfoExt);;
        System.out.println("111111111111111");
        return map;
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value="/stopUser.htmlx")
    @ResponseBody
    public Map  stopUser(HttpServletRequest request ,UserInfoExt userInfoExt){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        sysLogService.add("停止用户", IpUtil.getIpAddr(request), "管理", user.getId()+"", user.getUser_name());
        userInfoExtService.stopUser(userInfoExt);
        Map map =new HashMap();
        map.put("result", "success");
        return map;
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value="/startUser.htmlx")
    @ResponseBody
    public Map  startUser(HttpServletRequest request ,UserInfoExt userInfoExt){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        sysLogService.add("开启用户", IpUtil.getIpAddr(request), "管理", user.getId()+"", user.getUser_name());
        userInfoExtService.startUser(userInfoExt);
        Map map =new HashMap();
        map.put("result", "success");
        return map;
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value="/deleteUser.htmlx")
    @ResponseBody
    public Map  deleteUser(HttpServletRequest request ,String ids){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        sysLogService.add("删除用户", IpUtil.getIpAddr(request), "管理", user.getId()+"", user.getUser_name());
        Map map =new HashMap();
        if(ids!=null){
            String[] id=ids.split(",");
            for(String s:id){

                System.out.println(s);
                userInfoExtService.delete(s);
            }
        }
        map.put("result", "success");
        System.out.println("111111111111111");
        return map;
    }
    @RequestMapping(value="/users-change-password.htmlx")
    public String  usersChangePassword(ModelMap model,UserInfoExt userInfoExt){
        UserInfoExt info=null;
        if(userInfoExt.getId()!=null){
            info= userInfoExtService.get(userInfoExt.getId());
            model.addAttribute("adminUser",info);
        }
        System.out.println("111111111111111");
        return "user/users-change-password";
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value="/changeUserPsw.htmlx")
    @ResponseBody
    public Map  changeUserPsw(HttpServletRequest request ,ModelMap model,UserInfoExt userInfoExt){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        sysLogService.add("更改用户密码", IpUtil.getIpAddr(request), "管理", user.getId()+"", user.getUser_name());
        Map map =new HashMap();
        userInfoExtService.changeUserPsw(userInfoExt);
        map.put("result", "success");
        System.out.println("111111111111111");
        return map;
    }


    /**
     * 批量导入模板下载
     */
    @RequestMapping("/downLoad.htmlx")
    public void downLoad(HttpServletRequest request, HttpServletResponse response){
        String realPath = this.getClass().getClassLoader().getResource("/").getPath()+"用户.xlsx";
        try {
            String fileName = new String("用户模板.xlsx".getBytes("utf-8"),"iso-8859-1");
            response.setHeader("content-disposition","attachment;filename="+fileName);
            InputStream in = new FileInputStream(realPath);
            int len = 0;
            byte[] b = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = in.read(b))!=-1){
                out.write(b,0,len);
            }
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化批量修改用户
     */
    @RequestMapping("/users-update-all.htmlx")
    public String initUsersUpdateAll(HttpServletRequest request,UsersBo usersBo){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        if("2".equals(user.getType())){
            usersBo.setDomain(user.getDomain());
        }
        List list = domainService.getDomainInfoExt(usersBo);
        request.setAttribute("domainList",list);
        return "user/user-update-all";
    }

    /**
     * 批量修改用户
     */
    @RequestMapping(value = "/userUpdateBatch.htmlx",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateUserBatch(HttpServletRequest request){
        Map<String,Object> rs = new HashMap<String, Object>();
        String domain = request.getParameter("domain");
        String remark = request.getParameter("remark");
        List<UserInfoExt> list = new ArrayList<UserInfoExt>();
        if(org.apache.commons.lang.StringUtils.isNotEmpty(remark)|| org.apache.commons.lang.StringUtils.isNotBlank(remark)){
            String[] split = remark.split("\\n");
            if(split.length<1){
                rs.put("msg","01");
            }else{
                UsersBo usersBo = new UsersBo();
                usersBo.setDomain(domain);
                DomainInfoExt domainInfoExtByDomain = domainInfoExtService.getDomainInfoExtByDomain(domain);
                String maxStoreCount = domainInfoExtByDomain.getMax_store_count();
                String DiskStoreCount = domainInfoExtByDomain.getDisk_store_count();
                if(maxStoreCount==null){
                    maxStoreCount="0";
                }
                if(DiskStoreCount==null){
                    DiskStoreCount="0";
                }

                Long max_store_count = Long.valueOf(maxStoreCount);
                Long disk_store_count = Long.valueOf(DiskStoreCount);
               // List<UserInfoExt> allUser = (List<UserInfoExt>)userInfoExtService.getAllUser(usersBo);
                for(String s:split ){
                    UserInfoExt user = new UserInfoExt();
                    user.setDomain(domain);
                    String[] split1 = s.split(",");
                    if(org.apache.commons.lang.StringUtils.isNotBlank(split1[0])){
                        user.setUser_name(split1[0]+"@"+domain);
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(split1[1])){
                        user.setPassword(split1[1]);
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(split1[2])){
                        long remaxStorecount =Long.valueOf(split1[2]);
                        if(max_store_count!=0){
                            if(remaxStorecount>max_store_count){
                                rs.put("msg","03");
                                return rs;
                            }
                        }

                        user.setMax_mail_box_size(Long.valueOf(split1[2]));
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(split1[3])){
                        long remaxDiskStorecount =Long.valueOf(split1[3]);
                        if(disk_store_count!=0){
                            if(remaxDiskStorecount>disk_store_count){
                                rs.put("msg","04");
                                return rs;
                            }
                        }

                        user.setMax_message_size(Long.valueOf(split1[3]));
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(split1[4])){
                        user.setName(split1[4]);
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(split1[5])){
                        user.setWork_no(split1[5]);
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(split1[6])&&"on".equals(split1[6])){
                        user.setStatus("Y");
                    }
                    if(org.apache.commons.lang.StringUtils.isNotBlank(split1[6])&&"off".equals(split1[6])){
                        user.setStatus("N");
                    }
                    list.add(user);
                }
                if(userInfoExtService.batchUpdate(list)>0){
                    rs.put("msg","02");
                }

            }
        }

        return rs;
    }
    /**
     * 用户导入导出页面初始化
     */
    @RequestMapping("/users-import-export.htmlx")
    public String initImportAndExportPage(HttpServletRequest request,UsersBo usersBo){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        if("2".equals(user.getType())){
            usersBo.setDomain(user.getDomain());
        }
        List list = domainService.getDomainInfoExt(usersBo);
        request.setAttribute("domainList",list);
        return "user/user-import-export";
    }

    /**
     * 用户导入
     */
    @RequestMapping("/importData.htmlx")
    @ResponseBody
    public Map<String,Object> importData(){
        Map<String,Object> rs = new HashMap<String, Object>();

        return rs;
    }
    /**
     * 邮箱导出
     */
    @RequestMapping("/exportExcelData.htmlx")
    public void exportExcelData(@RequestParam("fileName")String fileName,@RequestParam("domain")String domain,HttpServletResponse response,HttpServletRequest request,UsersBo usersBo){
        AdminUser user = (AdminUser) request.getSession().getAttribute("user");
        usersBo.setDomain(domain);
        List list = userInfoExtService.getAllUser(usersBo);
        String jsonString = JSON.toJSONString(list);
        JSONArray array = JSON.parseArray(jsonString);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Map<String,String> headMap = new HashMap<String, String>();
        headMap.put("id","id");
        headMap.put("email","邮箱");
        headMap.put("name","姓名");
        headMap.put("sex","性别");
        headMap.put("domian","域名");
        headMap.put("status","状态");
        headMap.put("phone","手机");
        headMap.put("address","地址");
        headMap.put("grouid","组ID");
        headMap.put("maxs","邮箱容量");
        headMap.put("wanpan","网盘容量");
        headMap.put("hanvse","已使用网盘容量");
        headMap.put("autor","自动回复状态");
        headMap.put("autstuat","自动转发状态");
        headMap.put("autoaddress","自动转发地址");
        headMap.put("account","帐号类型");
        headMap.put("depatemenId","部门ID");
        headMap.put("ceratimen","创建时间");
        headMap.put("gonghao","工号");
        headMap.put("beizhu","备注");

        String[] title={"姓名","性别","邮箱","密码","手机","状态","地址","备注","邮箱容量","网盘容量","公积金帐号"};
       // PoiExcelUtil.exportExcel(fileName+".xlsx",title,list,response);
        String realPath = this.getClass().getClassLoader().getResource("/").getPath()+"备份.xlsx";
        ExcelUtil.createUTPExcel(fileName+".xlsx",realPath,title,list,response);
      //  ExcelUtil.downloadExcelFile(fileName,headMap,array,response);

    }
    /**
     * 根据邮箱帐号查找用户
     */
    @RequestMapping("/getUserInfoByUserName.htmlx")
    @ResponseBody
    public Map<String,Object> getUserInfoByUserName(@RequestParam("email")String email){

        Map<String,Object> rs  = new HashMap<String, Object>();
        UserInfoExt info  = userInfoExtService.getUserInfoByUserName(email);
        if(info==null){
            rs.put("msg","error");
        }
        return rs;
    }
}
  